<template>
  <el-dialog v-model="visible" title="绑定策略" width="880px">
    <div class="bind-strategy-box">
      <div class="strategy-list strategy-all">
        <h2 class="strategy-list-title">所有策略</h2>
        <ul class="strategy-list-ul" v-loading="loading">
          <el-scrollbar>
            <li v-for="item in strategyCheckList" :key="item.id">
              <el-checkbox v-model="item.checked" @change="changeCheckStrategy(item)" style="margin-right: 10px" />
              <div @click.stop="handleCheckStrategy(item)">
                <p class="strategy-name">{{ item.name }}</p>
                <p class="strategy-desc">{{ item.description }}</p>
              </div>
              <el-button text type="primary" @click="showStrategyPermission(item)">查看权限</el-button>
            </li>
          </el-scrollbar>
        </ul>
      </div>

      <div class="strategy-list strategy-this">
        <h2 class="strategy-list-title">
          已绑定策略
          <span>{{ userStrategyList.length }}/5</span>
        </h2>
        <div class="strategy-list-box">
          <div class="strategy-list-item" v-for="item in userStrategyList" :key="item.id">
            <p>{{ item.name }}</p>
            <el-icon @click="removeStrategy(item)"><Delete /></el-icon>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submit" :loading="submitting">确认</el-button>
        <el-button @click="close">取消</el-button>
      </span>
    </template>
    <!-- 查看权限 -->
    <StrategySetting v-if="isShowPermission" v-model:show="isShowPermission" :authList="authList" :resourceAuthGroupId="curStrategyId" :disabled="true" />
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getResourceAuthGroupList, getUserResourceAuthGroup, bindUserResourceAuthGroup, getAuthList } from '@/api/strategy'
import StrategySetting from './StrategySetting.vue'

const props = defineProps({
  modelValue: Boolean,
  userId: Number
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

const loading = ref(false)
const submitting = ref(false)
const strategyList = ref([])
const userStrategyList = ref([])
const isShowPermission = ref(false)
const authList = ref([])

// 计算选中状态
const strategyCheckList = computed(() => {
  const checkedIds = userStrategyList.value.map(item => item.id)
  return strategyList.value.map(item => ({
    ...item,
    checked: checkedIds.includes(item.id)
  }))
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 加载权限列表
    const authRes = await getAuthList()
    authList.value = authRes.data

    // 加载策略数据
    const [strategies, userStrategies] = await Promise.all([getResourceAuthGroupList(), getUserResourceAuthGroup({ id: props.userId })])
    strategyList.value = strategies.data
    userStrategyList.value = userStrategies.data
  } finally {
    loading.value = false
  }
}

// 选择策略
const changeCheckStrategy = data => {
  if (data.checked) {
    if (userStrategyList.value.length >= 5) {
      data.checked = false
      ElMessage.warning('最多绑定5个策略')
      return
    }
    userStrategyList.value.push(data)
  } else {
    userStrategyList.value = userStrategyList.value.filter(item => item.id !== data.id)
  }
}

const handleCheckStrategy = data => {
  changeCheckStrategy(data)
}

// 移除策略
const removeStrategy = data => {
  userStrategyList.value = userStrategyList.value.filter(item => item.id !== data.id)
}

// 查看权限
const curStrategyId = ref('')
const showStrategyPermission = async data => {
  curStrategyId.value = data.id
  isShowPermission.value = true
}

// 提交
const submit = async () => {
  submitting.value = true
  try {
    await bindUserResourceAuthGroup({
      resourceAuthGroupIds: userStrategyList.value.map(item => item.id),
      userId: props.userId
    })
    ElMessage.success('绑定成功')
    emit('success')
    close()
  } finally {
    submitting.value = false
  }
}

const close = () => {
  visible.value = false
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.bind-strategy-box {
  display: flex;
  justify-content: space-between;
  height: 475px;

  .strategy-list {
    background-color: #f7f9fd;
    height: 100%;
    padding: 0 10px 10px;
    box-sizing: border-box;

    h2.strategy-list-title {
      font-size: 14px;
      font-weight: normal;
      padding: 15px 0;

      span {
        color: #666;
        margin-left: 4px;
      }
    }

    &.strategy-all {
      width: 430px;

      .strategy-list-ul {
        width: 100%;
        padding: 10px 0 0;
        height: 360px;

        li {
          list-style: none;
          display: flex;
          width: 100%;
          height: 40px;
          align-items: center;
          border-bottom: 1px solid #dcdfe6;

          div {
            display: flex;
            height: 100%;
            align-items: center;
            cursor: pointer;

            p {
              &.strategy-name {
                width: 120px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }

              &.strategy-desc {
                width: 180px;
                color: #909399;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
      }
    }

    &.strategy-this {
      width: 390px;

      .strategy-list-box {
        .strategy-list-item {
          width: 100%;
          height: 50px;
          align-items: center;
          display: flex;
          border-radius: 4px;
          background-color: #fff;
          box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
          margin-bottom: 10px;
          padding: 0 15px;
          box-sizing: border-box;
          justify-content: space-between;

          i {
            font-size: 18px;
            cursor: pointer;
            color: #409eff;
          }
        }
      }
    }
  }
}
</style>
